package br.com.generic.dao.impl;

import java.io.Serializable;
import java.util.List;

import org.hibernate.Session;

import br.com.techfor.generic.dao.GenericDAO;
import br.com.techfor.hibernate.util.HiberntateUtil;

/**
 * 
 * @author alex.amaral
 * 
 * @param <T>
 */
public class GenericDAOImpl<T, PK> implements GenericDAO<T, PK> {

	private Session session;
	private Class<T> classe;

	public GenericDAOImpl(Class<T> classe) {
		this.classe = classe;
	}

	public void salvar(T bean) {
		this.session = HiberntateUtil.getFactory().openSession();
		this.session.beginTransaction();
		this.session.save(bean);
		this.session.getTransaction().commit();
		this.session.close();

	}

	public void atualizar(T bean) {
		this.session = HiberntateUtil.getFactory().openSession();
		this.session.beginTransaction();
		this.session.update(bean);
		this.session.getTransaction().commit();
		this.session.close();

	}

	public void deletar(T bean) {

		this.session = HiberntateUtil.getFactory().openSession();
		this.session.beginTransaction();
		this.session.delete(bean);
		this.session.getTransaction().commit();

		this.session.close();

	}

	@SuppressWarnings("unchecked")
	public T getBean(PK codigo) {
		this.session = HiberntateUtil.getFactory().openSession();
		this.session.beginTransaction();
		T bean = (T) this.session.get(this.classe, (Serializable) codigo);
		this.session.getTransaction().commit();
		this.session.close();
		return bean;
	}

	@SuppressWarnings("unchecked")
	public List<T> getBeans() {
		this.session = HiberntateUtil.getFactory().openSession();
		this.session.beginTransaction();
		List<T> beans = (List<T>) this.session.createCriteria(this.classe)
				.list();
		this.session.getTransaction().commit();
		this.session.close();
		return beans;
	}

	@SuppressWarnings("unchecked")
	public T carrega(PK pk) {
		return (T) this.session.load(this.classe, (Serializable) pk);
	}

	public Session getSession() {
		return session;
	}

	public void setSession(Session session) {
		this.session = session;
	}

	public Class<T> getClasse() {
		return classe;
	}

	public void setClasse(Class<T> classe) {
		this.classe = classe;
	}

}
